package com.lovo.boot.controller;

import com.lovo.boot.annotation.ResponseResult;
import com.lovo.boot.exception.GlobalHandleException;
import com.lovo.boot.model.dos.UserDO;
import com.lovo.boot.model.dto.UserDTO;
import com.lovo.boot.model.query.UserQuery;
import com.lovo.boot.service.UserService;
import com.lovo.boot.util.PojoTransferUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * @title
 * @author: luo
 * @date: 2020/11/24 16:57
 */
@RestController
@ResponseResult
@RequestMapping("/api/users")
@Api(tags = "用户相关接口")
public class UserController {
    @Resource
    private UserService userService;

    @GetMapping
    @ApiOperation("分页查询用户接口")
    public Object find(UserQuery userQuery) {
        return userService.findAll(userQuery);
    }

    @PostMapping
    @ApiOperation("新增用户接口")
    @ResponseStatus(HttpStatus.CREATED)
    public Object add(@Valid @RequestBody UserDTO userDTO) throws GlobalHandleException {
        UserDO userDO = PojoTransferUtil.transfer(userDTO, UserDO.class);
        return userService.addUser(userDO);
    }

    @DeleteMapping("/{userId}")
    @ApiOperation("删除用户接口")
    @ApiImplicitParam(name = "userId", value = "1", example = "1")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void delete(@PathVariable("userId") String userId) throws GlobalHandleException {
        userService.deleteUser(userId);
    }

    @PutMapping("/{userId}")
    @ApiOperation("更新用户接口")
    public Object update(@PathVariable("userId") String userId, @RequestBody UserDTO userDTO) throws GlobalHandleException {
        UserDO userDO = PojoTransferUtil.transfer(userDTO, UserDO.class);
        userDO.setUserId(userId);
        return userService.updateUser(userDO);
    }

    @PostMapping("/login")
    @ApiOperation("用户登录接口")
    public Object login(@RequestBody UserDTO userDTO, HttpServletRequest request) throws GlobalHandleException {
        UserDO userDO = PojoTransferUtil.transfer(userDTO, UserDO.class);
        UserDO loginUser = userService.login(userDO);
        request.getSession().setAttribute("loginUser", loginUser);
        return loginUser;
    }

    @GetMapping("/{userId}")
    public Object findById(@PathVariable("userId") String userId) throws GlobalHandleException {
        UserDO userDO = userService.findByUserId(userId);
        return userDO;
    }

}
